package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseApp;
import com.atguigu.realtime.bean.TrafficPageViewBean;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2023/3/18 08:31
 */
public class Dws_02_DwsTrafficVcChArIsNewPageViewWindow extends BaseApp {
    public static void main(String[] args) {
        new Dws_02_DwsTrafficVcChArIsNewPageViewWindow().init(
            4002,
            2,
            "Dws_02_DwsTrafficVcChArIsNewPageViewWindow",
            Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
        
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        // 1. 解析数据, 封装到 pojo 中
        SingleOutputStreamOperator<TrafficPageViewBean> beanStream = parseToPojo(stream);
        // 2. 开窗聚合
        SingleOutputStreamOperator<TrafficPageViewBean> resultStream = windowAndAgg(beanStream);
    
    
        // 3. 写出到 clickhouse 中
        writeToClickHouse(resultStream);
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<TrafficPageViewBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_traffic_vc_ch_ar_is_new_page_view_window", TrafficPageViewBean.class));
    }
    
    private SingleOutputStreamOperator<TrafficPageViewBean> windowAndAgg(SingleOutputStreamOperator<TrafficPageViewBean> beanStream) {
        /*
        时间
            处理
            事件
        个数
        
        窗口处理函数:
            简单(都是增量处理)
                sum
                max maxBy
                min minBy
            
            复杂
                reduce(增量)
                    处理后的类型和处理前一样
                aggregate(增量)
                    处理后的类型和处理前不一样
                    因为: 有一个累加器(中间结果)
                process(全量)
                    前面的都处理不了
                        窗口排序
                        测输出流
            
            
         */
       return beanStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TrafficPageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
                    .withIdleness(Duration.ofSeconds(60)) // 如果一个并行度的水印超过 60s 没更新, 则依其他的水印为准进行水印的传递
            
            )
            .keyBy(bean -> bean.getCh() + "_" + bean.getVc() + "_" + bean.getAr() + "_" + bean.getIsNew())
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TrafficPageViewBean>() {
                    @Override
                    public TrafficPageViewBean reduce(TrafficPageViewBean value1,
                                                      TrafficPageViewBean value2) throws Exception {
                        value1.setPvCt(value1.getPvCt() + value2.getPvCt());
                        value1.setUvCt(value1.getUvCt() + value2.getUvCt());
                        value1.setSvCt(value1.getSvCt() + value2.getSvCt());
                        value1.setDurSum(value1.getDurSum() + value2.getDurSum());
    
                        return value1;
                    }
                },
                new ProcessWindowFunction<TrafficPageViewBean, TrafficPageViewBean, String, TimeWindow>() {
                    @Override
                    public void process(String key,
                                        Context ctx,
                                        Iterable<TrafficPageViewBean> elements, // 有且仅有一个元素: 是 前面reduce 函数聚和的最终结果
                                        Collector<TrafficPageViewBean> out) throws Exception {
    
                        TrafficPageViewBean bean = elements.iterator().next();
    
                        bean.setStt(AtguiguUtil.tsToDateTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.tsToDateTime(ctx.window().getEnd()));
                        
                        bean.setTs(System.currentTimeMillis());  // 设置为数据统计的时间
    
    
                        out.collect(bean);
    
    
                    }
                }
            );
        
        
    }
    
    private SingleOutputStreamOperator<TrafficPageViewBean> parseToPojo(DataStreamSource<String> stream) {
        return stream
            .map(JSON::parseObject)
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
            .map(new RichMapFunction<JSONObject, TrafficPageViewBean>() {
                
                private ValueState<String> lastVisitDateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastVisitDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastVisitDate", String.class));
                }
                
                @Override
                public TrafficPageViewBean map(JSONObject obj) throws Exception {
                    Long ts = obj.getLong("ts");
                    JSONObject common = obj.getJSONObject("common");
                    String vc = common.getString("vc");
                    String ch = common.getString("ch");
                    String ar = common.getString("ar");
                    String isNew = common.getString("is_new");
                    
                    JSONObject page = obj.getJSONObject("page");
                    Long pvCt = 1L;  // pv一定是 1, 每条访问日志都会对 pv 贡献 1
                    Long durSum = page.getLong("during_time");
                    
                    long uvCt = 0L;
                    // 如果是这个 mid 的当天的第一条数据, 则应该把 uvCt = 1L
                    // 定义一个键控状态: 存储这个 mid 最后一次访问的年月日
                    String lastVisitDate = lastVisitDateState.value();
                    String today = AtguiguUtil.tsToDate(ts);
                    if (!today.equals(lastVisitDate)) {
                        // 证明是这个 mid 的今天的第一条数据访问
                        uvCt = 1L;
                        // 更新状态
                        lastVisitDateState.update(today);
                    }
                    long svCt = 0L;
                    // 如何判断是否为一个新的会话?  last_page_id = null
                    // 如果没有last_page_id, 预计会有 session_id
                    if (page.getString("last_page_id") == null) {
                        svCt = 1L;
                    }
                    
                    return new TrafficPageViewBean("", "",
                                                   vc, ch, ar, isNew,
                                                   uvCt, svCt, pvCt, durSum,
                                                   ts
                    );
                }
            });
    }
}
/*

流量域:版本-渠道-地区-访客类别粒度页面浏览各窗口汇总

版本-渠道-地区-访客类别: 维度 groupBy ...

开窗

直接读取页面日志: 根据每条数据的的特点, 决定 pv uv   sv
---------

版本 渠道 地区   pv uv   sv
a    hw  北京   1   1   1
a    hw  北京   1   0   0
....
------
keyBy: 窗口 版本 渠道 地区
开窗聚和:
---------
窗口 版本 渠道 地区   pv uv   sv
0-5  a   hw  北京   10  1    1
0-5  b   hw  北京   10  1    1
....



*/